import Shop from '../../model/shop'
import DlyAdminUser from '../../model/dlyadminuser'
import Orders from '../../model/orders'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
import AiPayOrder from '../../model/AiPayOrder'
import dlyadminOrderStinetsSchema from '../../model/dlyadminOrderStinets'
import mongoose from 'mongoose'
import XLSX from 'xlsx'

class OrdersController {
	static async serviceMarketlist(ctx) {
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		// console.log('jwtuserinfo', jwtuserinfo)
		const {
			page = 1,
			pageSize = 20,
			// isBuy = '',
			shop_id = '',
			// shop_name = '',
			shop_phone = '',
			user_phone = '',
			isProxy = '',
			proxyPhone = '',
			order_id = '',
			isRefund = '',
			pay_type = '',
			start_time = '',
			end_time = '',
			isSettle = '',
		} = ctx.query
		const param = {
			shop_id: shop_id * 1,
			order_id,
			isRefund: isRefund * 1,
			pay_type: pay_type * 1,
			isSettle: isSettle * 1,
		}
		if (
			jwtuserinfo.roleName === 'adminSp' ||
			jwtuserinfo.roleName === 'admin'
		) {
			param.proxyId = ''
		}
		if (jwtuserinfo.roleName === 'proxy1') {
			const pritids = await DlyAdminUser.find({
				parentId: jwtuserinfo._id,
			})
			if (pritids.length > 0) {
				const litsadrtid = [
					jwtuserinfo._id,
					...pritids.map((item) => item._id),
				]
				param.proxyId = { $in: litsadrtid }
			} else {
				// 转换数据库id
				param.proxyId = mongoose.Types.ObjectId(jwtuserinfo._id)
			}
		}
		if (jwtuserinfo.roleName === 'proxy2') {
			param.proxyId = mongoose.Types.ObjectId(jwtuserinfo._id)
		}
		if (proxyPhone != '') {
			const getProxyData = await DlyAdminUser.findOne({
				phone: proxyPhone,
			})
			if (!getProxyData) {
				ctx.body = { list: [], total: 0 }
				return
			}
			param.proxyId = getProxyData._id
		}
		if (start_time && end_time) {
			param.createTime = {
				$gte: new Date(start_time),
				$lte: new Date(end_time),
			}
		}
		for (let key in param) {
			if (!param[key]) delete param[key]
		}

		//pay_amount 字段求和
		console.log('param', param)
		const listw = await Orders.aggregate([
			{ $match: param },
			{
				$group: {
					_id: null,
					allPayNum: { $sum: '$pay_amount' },
					allSettleNum: { $sum: '$settleAmount' },
				},
			},
		])
		// ctx.body = listw
		const list = await Orders.find(param)
			.populate('proxyId')
			.populate('proxyLinkId')
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)
			.sort({ createTime: -1 })

		const total = await Orders.countDocuments(param)
		const summing = {
			allPayNum: listw[0] ? listw[0].allPayNum : 0,
			allSettleNum: listw[0] ? listw[0].allSettleNum : 0,
		}
		ctx.body = { list, total, summing }
	}
	static async alipayOrders(ctx) {
		// ctx.body = '支付宝订单'
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		if (
			jwtuserinfo.roleName !== 'adminSp' &&
			jwtuserinfo.roleName !== 'admin'
		) {
			throw new ApiError(ApiErrorNames.NO_PERMISSION)
		}
		const {
			page = 1,
			pageSize = 20,
			subject = '',
			status = '',
			func_name = '',
			start_time = '',
			end_time = '',
		} = ctx.query
		const param = {
			subject,
			status,
			func_name,
		}
		if (param.subject) {
			param.subject = { $regex: param.subject, $options: 'i' }
		}
		if (start_time && end_time) {
			param.createTime = {
				$gte: new Date(start_time),
				$lte: new Date(end_time),
			}
		}
		for (let key in param) {
			if (!param[key]) delete param[key]
		}
		if (param.func_name && param.func_name == 'AI') {
			// 筛选null 或者 AI
			param.func_name = { $in: [null, 'AI'] }
		}
		const list = await AiPayOrder.find(param)
			.populate('order_user_id')
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)
			.sort({ createTime: -1 })
		const total = await AiPayOrder.countDocuments(param)
		ctx.body = { list, total }
	}
	static async uporderFile(ctx) {
		const { file } = ctx.request.files
		const { type } = ctx.request.body
		if (file) {
			if (file.mimetype === 'text/csv') {
				const workbook = XLSX.readFile(file.filepath, {
					type: 'binary',
					cellDates: true,
				})
				const sheetNames = workbook.SheetNames
				const sheet = workbook.Sheets[sheetNames[0]]
				for (let cell in sheet) {
					if (cell[0] === 'A' && cell !== 'A1') {
						sheet[cell].t = 's'
						sheet[cell].v = sheet[cell].w.replace('\t', '')
					}
					if (
						cell[0] === 'G' ||
						cell[0] === 'H' ||
						cell[0] === 'I' ||
						cell[0] === 'K' ||
						(cell[0] === 'L' &&
							cell !== 'G1' &&
							cell !== 'H1' &&
							cell !== 'I1' &&
							cell !== 'K1' &&
							cell !== 'L1')
					) {
						sheet[cell].t = 'n'
						const regex = new RegExp(`^¥`)
						sheet[cell].v = sheet[cell].v.replace(regex, '')
					}
				}
				const data = XLSX.utils.sheet_to_json(sheet)
				// console.log('data+++', data)
				const getEndOrder = data.filter((item) => {
					if (item['结算状态'] == '已结算') {
						item['结算总额'] = data
							.filter((endOrders) => {
								return endOrders['订单号'] == item['订单号']
							})
							.map((endOrders) => {
								return endOrders['实际结算金额'] * 1
							})
							.reduce((pre, cur) => pre + cur, 0)
							.toFixed(2) * 1
					}
					return item['结算状态'] == '已结算'
				})
				console.log('getEndOrder', getEndOrder[160])

				// 批量更新 Orders 表 的isSettle
				if (getEndOrder.length > 0) {
					for (let i = 0; i < getEndOrder.length; i++) {

						await Orders.updateMany(
							{ order_id: getEndOrder[i]['订单号'] },
							{
								isSettle: 1,
								settleAmount: getEndOrder[i]['结算总额'],
							}
						)
						console.log('getEndOrder[i]', { order_id: getEndOrder[i]['订单号'] }, {
							isSettle: 1,
							settleAmount: getEndOrder[i]['结算总额'],
						}, getEndOrder.length, i)
					}
				}
				// const getOrderData = await Orders.find({
				// 	order_id: getEndOrder[160]['订单号'],
				// })
				// console.log('getOrderData', getOrderData)
			}
		}
		// console.log('type', type, file.mimetype)
		const path = file.filepath
		const name = file.name
		const url = `http://localhost:3000/${path}`
		const data = {
			name,
			url,
			type,
		}
		ctx.body = data
	}
	static async proxyMayMarket(ctx) {
		// const { url } = ctx.request.body
		// const { data } = await axios.get(url)
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		console.log('jwtuserinfo', jwtuserinfo)
		// 1 查询代理信息 获取最新的代理提成点
		if (jwtuserinfo) {
			const getProxyUser = await DlyAdminUser.findOne({
				_id: jwtuserinfo._id,
			})

			// 需要获取到下一级代理的提成点给到用户，然后用户再给下一级代理*******
			console.log('getProxyUser', getProxyUser)
			const { point, roleName } = getProxyUser
			// 2. 查询订单信息 获取待结算的金额
			const param = {
				// isRefund: isRefund * 1,
				// pay_type: pay_type * 1,
				proxyId: mongoose.Types.ObjectId(jwtuserinfo._id),
				isSettle: 1,
				// isSettleProxy: {
				// 	$in: [null, 0],
				// },
				// proxygetmay: {
				// 	$in: [null, false],
				// },
			}

			const param2 = {
				// isRefund: isRefund * 1,
				// pay_type: pay_type * 1,
				proxyId: mongoose.Types.ObjectId(jwtuserinfo._id),
				isSettle: {
					$in: [null, 0],
				},
				// isSettleProxy: {
				// 	$in: [null, 0],
				// },
				// proxygetmay: {
				// 	$in: [null, false],
				// },
			}

			param[`${roleName}getmay`] = {
				$in: [null, false],
			}

			param2[`${roleName}getmay`] = {
				$in: [null, false],
			}

			param[`${roleName}Settle`] = {
				$in: [null, 0],
			}

			param2[`${roleName}Settle`] = {
				$in: [null, 0],
			}
			if (roleName == 'adminSp') {
				// proxyId 不为空

				param.proxyId = {
					$ne: null,
				}
				param2.proxyId = {
					$ne: null,
				}
			}
			if (roleName == 'admin' || roleName == 'proxy1') {
				// proxyId 不为空
				const getLitser = await DlyAdminUser.find({
					parentId: mongoose.Types.ObjectId(jwtuserinfo._id),
				}).limit(1000)
				param.proxyId = {
					$in: [
						mongoose.Types.ObjectId(jwtuserinfo._id),
						...getLitser.map((item) =>
							mongoose.Types.ObjectId(item._id)
						),
					],
				}
				param2.proxyId = {
					$in: [
						mongoose.Types.ObjectId(jwtuserinfo._id),
						...getLitser.map((item) =>
							mongoose.Types.ObjectId(item._id)
						),
					],
				}
			}
			// const staeyr = {}
			// staeyr[`${roleName}getmay`] = false
			// staeyr[`${roleName}Settle`] = 0
			// await Orders.updateMany(param, {
			// 	proxygetmay: false,
			// 	...staeyr,
			// })

			// if (roleName == 'proxy1') {
			// 	// 需要查询到下级的子代理
			//    const getLitser = await DlyAdminUser.find({
			//         parentId: mongoose.Types.ObjectId(jwtuserinfo._id),
			//     })
			// }

			const listw = await Orders.aggregate([
				{ $match: param },
				{
					$group: {
						_id: null,
						// allPayNum: { $sum: '$pay_amount' },
						allSettleNum: { $sum: '$settleAmount' },
					},
				},
			])

			const listw2 = await Orders.aggregate([
				{ $match: param2 },
				{
					$group: {
						_id: null,
						// allPayNum: { $sum: '$pay_amount' },
						allNotNumSub: { $sum: '$pay_amount' },
					},
				},
			])

			// console.log('listw', listw)
			// let point = 50
			ctx.body = {
				allSettleNum: listw[0]
					? ((listw[0].allSettleNum * point) / 100).toFixed(2)
					: 0,

				allNotNumSub: listw2[0]
					? (((listw2[0].allNotNumSub / 100) * point) / 100).toFixed(
						2
					)
					: 0,
			}
			return
			// console.log('getProxyUser', getProxyUser)
		}
	}
	static async settlementOrder(ctx) {
		const {
			binkType = '1',
			userName = '',
			userNo = '',
			binkName = '',
			binkNo = '',
			userPhone = '',
			emaill = '',
		} = ctx.request.body

		const jwtuserinfo = ctx.request.header.jwtuserinfo
		// console.log('jwtuserinfo', jwtuserinfo)
		// return jwtuserinfo
		if (jwtuserinfo) {
			const param = {
				// isRefund: isRefund * 1,
				// pay_type: pay_type * 1,
				proxyId: mongoose.Types.ObjectId(jwtuserinfo._id),
				isSettle: 1,
				// isSettleProxy: {
				// 	$in: [null, 0],
				// },
				// proxygetmay: {
				// 	$in: [null, false],
				// },
			}
			const { roleName } = jwtuserinfo

			param[`${roleName}getmay`] = {
				$in: [null, false],
			}
			param[`${roleName}Settle`] = {
				$in: [null, 0],
			}
			if (roleName == 'adminSp') {
				// proxyId 不为空

				param.proxyId = {
					$ne: null,
				}
			}
			if (roleName == 'admin' || roleName == 'proxy1') {
				// proxyId 不为空
				const getLitser = await DlyAdminUser.find({
					parentId: mongoose.Types.ObjectId(jwtuserinfo._id),
				}).limit(1000)
				param.proxyId = {
					$in: [
						mongoose.Types.ObjectId(jwtuserinfo._id),
						...getLitser.map((item) =>
							mongoose.Types.ObjectId(item._id)
						),
					],
				}
			}
			const listw = await Orders.aggregate([
				{ $match: param },
				{
					$group: {
						_id: null,
						// allPayNum: { $sum: '$pay_amount' },
						allSettleNum: { $sum: '$settleAmount' },
					},
				},
			])
			if (!listw[0]) {
				throw new ApiError(ApiErrorNames.NOT_FOUND)
			}

			const getProxyUser = await DlyAdminUser.findOne({
				_id: jwtuserinfo._id,
			})

			// 需要获取到下一级代理的提成点给到用户，然后用户再给下一级代理*******
			console.log('getProxyUser', getProxyUser)
			const { point } = getProxyUser
			const addFormData = {
				proxyUserId: jwtuserinfo._id,
				parentId: jwtuserinfo.parentId,
				binkType,
				userName,
				userNo,
				binkName,
				binkNo,
				userPhone,
				emaill,
				applyTime: new Date(),
				applyMoney: listw[0]
					? ((listw[0].allSettleNum * point) / 100).toFixed(2)
					: 0, // 金额
			}
			if (!addFormData.applyMoney) {
				throw new ApiError(ApiErrorNames.NOT_FOUND)
			}
			const addResult = await dlyadminOrderStinetsSchema.create(
				addFormData
			)

			// 修改所有订单的提交状态
			// console.log('addResult', addResult)
			const intenterGetsconter = {}
			intenterGetsconter[`${roleName}getmay`] = true
			await Orders.updateMany(param, {
				proxygetmay: true,
				...intenterGetsconter,
			})

			ctx.body = '已提交， 等待审核'
			return
		}
	}
	static async puttlementOrder(ctx) {
		const {
			binkType = '1',
			userName = '',
			userNo = '',
			binkName = '',
			binkNo = '',
			userPhone = '',
			emaill = '',
		} = ctx.request.body

		const id = ctx.params.id
		await dlyadminOrderStinetsSchema.findByIdAndUpdate(id, {
			binkType,
			userName,
			userNo,
			binkName,
			binkNo,
			userPhone,
			emaill,
			status: 0,
			// applyTime: new Date(),
		})
		ctx.body = '已提交， 等待审核'
		// const jwtuserinfo = ctx.request.header.jwtuserinfo
		// if (jwtuserinfo) {

		// }
	}

	static async gettlementOrder(ctx) {
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		if (jwtuserinfo) {
			const param = {
				proxyUserId: jwtuserinfo._id,
			}
			const list = await dlyadminOrderStinetsSchema.find(param)
			ctx.body = { list }
			return
		}
	}

	static async getuserPuterList(ctx) {
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		if (jwtuserinfo) {
			const param = {
				parentId: jwtuserinfo._id,
			}
			const list = await dlyadminOrderStinetsSchema
				.find(param)
				.populate('proxyUserId')

			ctx.body = { list }
			return
		}
	}

	static async setMaPayStatus(ctx) {
		const id = ctx.params.id
		const { status, refuseRemark } = ctx.request.body
		console.log('setMaPayStatus', ctx.request.body, id)
		await dlyadminOrderStinetsSchema.findByIdAndUpdate(id, {
			status: status * 1,
			refuseRemark,
		})
		if (status == 1) {
			const proxy = await dlyadminOrderStinetsSchema.findById(id)
			console.log('list', proxy)
			const userInfo = await DlyAdminUser.findById(proxy.proxyUserId)
			const { roleName } = userInfo
			const param = {
				// isRefund: isRefund * 1,
				// pay_type: pay_type * 1,
				proxyId: mongoose.Types.ObjectId(proxy.proxyUserId),
				isSettle: 1,
				// isSettleProxy: {
				// 	$in: [null, 0],
				// },
				// proxygetmay: true,
			}

			if (roleName == 'adminSp') {
				// proxyId 不为空

				param.proxyId = {
					$ne: null,
				}
			}
			if (roleName == 'admin' || roleName == 'proxy1') {
				// proxyId 不为空
				const getLitser = await DlyAdminUser.find({
					parentId: mongoose.Types.ObjectId(proxy.proxyUserId),
				}).limit(1000)
				param.proxyId = {
					$in: [
						mongoose.Types.ObjectId(proxy.proxyUserId),
						...getLitser.map((item) =>
							mongoose.Types.ObjectId(item._id)
						),
					],
				}
			}
			const intenterGetsconter = {}
			intenterGetsconter[`${roleName}Settle`] = 1
			await Orders.updateMany(param, {
				isSettleProxy: 1,
				...intenterGetsconter,
			})
			// if(list) {
			//     await Orders.updateMany({proxyUserId: list.proxyUserId}, {isSettleProxy: 1})
			// }
		}
		ctx.body = 'ok'
	}
}

export default OrdersController
